package com.hfh.homework;

import org.junit.Test;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @Author hfh
 * @Date 2022 09 14 15 32
 **/
public class Work2 {
    @Test
    public void send() throws IOException {
        DatagramSocket ds = new DatagramSocket(8888);

        Scanner sc = new Scanner(System.in);
        while (true) {
            String str = sc.next();
            if ("bye".equals(str)) {
                break;
            }
            byte[] arr = str.getBytes();
            int len = arr.length;
            DatagramPacket dp = new DatagramPacket(arr, len, InetAddress.getLocalHost(), 9999);
            ds.send(dp);

            byte[] arr1 = new byte[1024];
            int len1 = arr1.length;
            DatagramPacket dp1 = new DatagramPacket(arr1, len1);

            ds.receive(dp1);
            arr1= dp.getData();
            len1 = dp.getLength();
            System.out.println("咨询人员："+new String(arr1,0, len1));


        }

        ds.close();

    }
    @Test
    public void receive() throws IOException {
        DatagramSocket ds = new DatagramSocket(9999);

        while(true){
            byte[] arr = new byte[1024];
            int len = arr.length;
            DatagramPacket dp = new DatagramPacket(arr, len);

            ds.receive(dp);
            arr= dp.getData();
            len = dp.getLength();
            System.out.println("客户："+new String(arr,0, len));
            if ("bye".equals(new String(arr,0, len))) {
                break;
            }

            DatagramPacket dp1 = new DatagramPacket("回答问题".getBytes(), "回答问题".getBytes().length, InetAddress.getLocalHost(), 8888);
            ds.send(dp1);
        }
        ds.close();
    }
}
